<?php
session_start();
error_reporting('E_ALL');
$self = $_SERVER['PHP_SELF'];

include 'functions.php';
include '../db-control/inc/functions.php';
include '../db-control/dbOpportunity.php';
include '../model/Opportunity.php';
include '../db-control/dbContact.php';
//include '../db-control/dbCategory.php';

if (!isLoggedIn()) {
   die("Please log in <a href='../'>HERE</a> first.");
}

if (!isManager()) {
   die("<a href='javascript:history.go(-1);'><<< Go Back - You are not authorized to view this page...</a>");
}

$message = saveItems();

$page = $_REQUEST['view'];
goToPage($page);
?>
<!DOCTYPE html>
<html>
   <head>
      <title>Admin | Internships</title>
      <link rel="stylesheet" type="text/css" href="../css/style.css" />
      <script type="text/javascript">
         function updateSearchField(){
            var val = search_form.elements["searchFor"].value;
            search_form.search.placeholder = val;
         }
         function submit(){
            document.forms["view_dropdown"].submit();
         }
      </script>
      <style type="text/css">
         textarea.edit{
            width:175px;
            height:50px;
            resize:none;
         }   
      </style>
   </head>
   <body>
      <form action="<?php echo $self; ?>" method="get">
         <table width="100%">
            <div align="left">
               <tr><td rowspan="7" valign="top"><img alt="" src="../img/unhmlogo.png" width="200px" height="120px" /></td></tr>
               <tr><td align="right" valign="top"><a href="../logout.php" title="Logout of the system.">Logout</a> | <a href="../help.php" title="View the help documentation.">?</a></td></tr>
               <tr><td width="100%" align="left"><h3 style="font-size:2em;">Internship 2 Career</h3><br /></td></tr>
               <tr><td align="left"><p>You can filter your searches by category, city, or a custom search:</p></td></tr>
               <tr>
                  <td align="left">
                     <form action="<?php echo $self; ?>" method="post" id="view_dropdown">
                        <font size="5">Manage:</font>
                        <?php
                        viewDropDown('internships');
                        ?>
                     </form>
                     <hr />
                  </td>
               </tr>
               <tr>
                  <td align="left">
                     <?php
                     categoryDropDown();
                     cityDropDown();
                     ?>
                  </td>
               </tr>
               <tr>
                  <td align="left">
                     <form action="<?php echo $self; ?>" method="get" id="search_form">
                        <?php
                        searchBox();
                        searchFor();
                        ?>
                     </form>
                  </td>
               </tr>
               <tr>
                  <td></td><td align="left"><?php ?></td>
               </tr>
            </div>
         </table>
         <table width="100%">
            <tr>
               <td valign="top" width="20%">
                  <?php editForm($message); ?>
               </td>
               <td width="5%"></td>
               <td width="75%">
                  <?php include 'internship_list.php'; ?>
               </td>
            </tr>
         </table>


      </form>
      <br /><br />

   </body>
</html>


<?php

function saveItems() {

   $id = $_POST['opportunity_id'];
   if (isset($_POST['edit_delete'])) {
      //user wants to delete the current opportunity
      if (!dbOpportunity::deleteFromOpportunity($id)) {
         return "Could not delete the selected internship!";
      } else {
         return "Internship deleted successfully!";
      }
   } else if (isset($_POST['edit_save'])) {
      //user is trying to save the opportunity details
      $orgID = $_POST['organization_id'];
      $contactID = $_POST['contact_id'];
      $title = $_POST['edit_title'];
      $numPos = $_POST['edit_numPositions'];
      $semester = $_POST['edit_semester'];
      $payRate = $_POST['edit_payRate'];
      $duration = $_POST['edit_duration'];
      $resp = $_POST['edit_resp'];
      $qual = $_POST['edit_qualifications'];
      $inst = $_POST['edit_instructions'];
      $comments = $_POST['edit_comments'];
      $categories = getCategoriesFromCheckboxes();

      $o = new Opportunity($orgID, $contactID, $title, $numPos, $semester, $payRate, $duration, $resp, $qual, $inst, $comments, $categories, 0, null);
      if (!dbOpportunity::updateOpportunity($id, $o)) {
         return "There was an error saving the internship.";
      } else {
         return "Internship saved successfully!";
      }
   }
}

function getCategoriesFromCheckboxes() {
   //loop through checkbox post
   $c = $_POST['cat'];
   for ($i = 0; $i < count($c); $i++) {
     $categories .= $c[$i] . " ";
   }
   return $categories;
}

function editForm($message) {

   //get the organization ID
   $orgID = $_POST['organization_id'];
   $conID = $_POST['contact_id'];
   $oppID = $_POST['opportunity_id'];
   if ($orgID != null) {
      //get the information associated with that ID
      $orgList = dbOrganization::getAllName();
      $contactList = dbContact::getAllName($orgID);
      dbOpportunity::getAllByID($oppID, $opp);
   }
   //fill in the forms
   $self = $_SERVER['PHP_SELF'];
   echo "<form action='$self' method='post'>";
   echo "<input type='hidden' name='opportunity_id' value='$oppID' />";
   echo "<table>";
   $dropDown = organizationDropDown($orgID, $orgList);
   echo "<tr><td colspan='2'><p class='error'>$message</p></td></tr>";
   echo "<tr><td valign='top' align='right'>Organization:</td><td>$dropDown</td></tr>";
   $dropDown = contactDropDown($conID, $contactList);
   echo "<tr><td valign='top' align='right'>Contact Person:</td><td>$dropDown</td></tr>";
   echo "<tr><td align='right'>Title:</td><td><input type='text' value='{$opp['title']}' name='edit_title' /></td></tr>";
   echo "<tr><td align='right'># of Positions:</td><td><input type='number' value='{$opp['numPositionsAvailable']}' name='edit_numPositions' /></td></tr>";
   echo "<tr><td align='right'>Semester:</td><td><input type='text' value='{$opp['semester']}' name='edit_semester' /></td></tr>";
   echo "<tr><td align='right'>Pay Rate:</td><td><input type='text' value='{$opp['payRate']}' name='edit_payRate' /></td></tr>";
   echo "<tr><td align='right'>Duration:</td><td><input type='text' value='{$opp['duration']}' name='edit_duration' /></td></tr>";
   echo "<tr><td valign='top' align='right'>Responsibilities:</td><td><textarea class='edit' name='edit_resp'>{$opp['responsibilities']}</textarea></td></tr>";
   echo "<tr><td valign='top' align='right'>Qualifications:</td><td><textarea class='edit' name='edit_qualifications'>{$opp['qualifications']}</textarea></td></tr>";
   echo "<tr><td valign='top' align='right'>Instructions:</td><td><textarea class='edit' name='edit_instructions'>{$opp['instructions']}</textarea></td></tr>";
   echo "<tr><td valign='top' align='right'>Comments:</td><td><textarea class='edit' name='edit_comments'>{$opp['comments']}</textarea></td></tr>";
   $categories = categorySystem($opp['categories']);
   echo "<tr><td valign='top' align='right' colspan='2'><a href='categories.php?action=edit'>edit</a><h1>Categories</h1><hr />$categories</td></tr>";
   //echo "<tr><td align='right'>Categories:</td><td><input type='text' value='{$opp['categories']}' name='edit_categories' /></td></tr>";
   echo "<tr>";
   if (isAdmin()) {
      echo "<td align='right'><input style='width:60px;' name='edit_delete' type='submit' value='Delete' /></td>";
   } else {
      echo "<td></td>";
   }
   echo "<td align='right'><input style='width:150px;' name='edit_save' type='submit' value='Save' /></td></tr>";
   echo "</table>";
   echo "</form>";
}

function categorySystem($categories) {
   //list box of all categories
   //user can select multiple categories
   $result = dbCategory::getAllCategories();
   $echo .= "<table width='100%'>";
   $echo .= "<tr><td valign='top' align='right'>";
   for ($i = 0; $i < mysql_num_rows($result); $i++) {
      $cat = mysql_fetch_assoc($result);
      if (strpos($categories, $cat['categoryName']) === false) {
         $checked = '';
      } else {
         $checked = "CHECKED";
      }
      if ($i == 10) {
         //start a new column
         $echo .= "</td><td valign='top' align='right'>";
      }
      $echo .= "<font size='1'>{$cat['categoryName']}</font><input $checked type='checkbox' style='width:20px;' name='cat[]' value='{$cat['categoryName']}'><br />";
   }
   $echo .= "</td></tr>";
   $echo .="</table>";

   return $echo;
}

function contactDropDown($id, $contacts) {
   if (!$contacts) {
      return;
   }
   $dropDown .= "<select name='contact_id'>";
   $dropDown .= "<option value=''>None</option>";
   for ($i = 0; $i < mysql_num_rows($contacts); $i++) {
      //for each row check to see if id is the same
      $row = mysql_fetch_assoc($contacts);
      $selected = ($row['contactID'] == $id) ? 'SELECTED' : null;
      $dropDown .= "<option $selected value='{$row['contactID']}'>{$row['fname']} {$row['lname']}</option>";
   }
   $dropDown .= "</select>";
   $dropDown .= "<br /><a title='Edit this contact.' href='contacts.php?action=edit&contactID='{$row['contactID']}'>edit</a> | <a title='Add a new contact.' href='contacts.php?action=add&orgID={$row['organizationID']}'>new</a>";
   return $dropDown;
}

function organizationDropDown($id, $organizations) {
   if (!$organizations) {
      return;
   }
   $dropDown .= "<select name='organization_id'>";
   for ($i = 0; $i < mysql_num_rows($organizations); $i++) {
      //for each row check to see if id is the same
      $row = mysql_fetch_assoc($organizations);
      $selected = ($row['organizationID'] == $id) ? 'SELECTED' : null;
      if ($selected != null) {
         $currentID = $row['organizationID'];
      }
      $dropDown .= "<option $selected value='{$row['organizationID']}'>{$row['organizationName']}</option>";
   }
   $dropDown .= "</select>";
   $dropDown .= "<br /><a title='Edit this organization.' href='organizations.php?action=edit&orgID=$currentID'>edit</a> | <a title='Add a new organization.' href='organizations.php?action=add'>new</a>";
   return $dropDown;
}

function searchFor() {
   if (isset($_REQUEST['searchFor'])) {
      $val = $_REQUEST['searchFor'];
      $_SESSION['searchFor'] = $val;
   } else {
      $val = $_SESSION['searchFor'];
   }
   switch ($val) {
      case 'Positions':
         $pos = 'SELECTED';
         break;
      case 'Qualifications':
         $qual = 'SELECTED';
         break;
      case 'Requirements':
         $req = 'SELECTED';
         break;
      case 'Organizations':
         $org = 'SELECTED';
         break;
   }
   echo "<select onchange='updateSearchField();' style='width:120px;' name='searchFor'>";
   echo "<option $pos value='Positions'>Positions</option>";
   echo "<option $qual value='Qualifications'>Qualifications</option>";
   echo "<option $req value='Responsibilities'>Responsibilities</option>";
   echo "<option $org value='Organizations'>Company</option>";
   echo "</select>";
}

function searchBox() {
   if (isset($_REQUEST['search'])) {
      $val = $_REQUEST['search'];
      $_SESSION['search'] = $val;
   } else {
      $val = $_SESSION['search'];
   }
   $ph = $_SESSION['searchFor'];
   echo "Search: <input type='search' title='Search for specific positions' name='search' onblur='this.form.submit();' placeholder='$ph' value='$val'/>";
}

/**
 * @desc Displays a select box for categories
 * @param string $name
 */
function categoryDropDown() {
   include '../db-control/dbCategory.php';
   $result = dbCategory::getAllCategories();
   if (isset($_REQUEST['categoryChange'])) {
      $catName = $_REQUEST['categoryChange'];
      $_SESSION['category'] = $catName;
   } else {
      $catName = $_SESSION['category'];
   }
   $numRows = mysql_num_rows($result);

   echo "<form action='$self' method='post'>";
   echo "Category: <select title='Select a category to only show internships in that category.' onchange='this.form.submit()' name='categoryChange'>";
   if ($catName == '') {
      echo "<option SELECTED value=''>Select a category...</option>";
   } else {
      echo "<option value=''>Show All</option>";
   }
   for ($i = 0; $i < $numRows; $i++) {
      $row = mysql_fetch_assoc($result);
      $name = $row['categoryName'];
      if ($row['categoryName'] == $catName) {
         echo "<option SELECTED value='$name'>$name</option>";
      } else {
         echo "<option value='$name'>$name</option>";
      }
   }
   echo "</select>";
   echo "</form>";
}

function cityDropDown() {
   include '../db-control/dbOrganization.php';
   $result = dbOrganization::getCities();
   if (isset($_REQUEST['cityChange'])) {
      $city = $_REQUEST['cityChange'];
      $_SESSION['city'] = $city;
   } else {
      $city = $_SESSION['city'];
   }

   $numRows = mysql_num_rows($result);
   echo "<form action='$self' method='get'>";
   echo "City: <select title='Select a city to filter internships by that location.' onchange='this.form.submit()' name='cityChange'>";
   if ($city == null) {
      echo "<option value=''>Select a city...</option>";
   } else {
      echo "<option value=''>Show All</option>";
   }
   for ($i = 0; $i < $numRows; $i++) {
      $row = mysql_fetch_assoc($result);
      if (strcmp($row['city'], $city) == 0) {
         echo "<option SELECTED value='" . $row['city'] . "'>" . $row['city'] . "</option>";
      } else {
         echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
      }
   }
   echo "</select>";
   echo "</form>";
}
?>
